package com.wangsh.userscenter.back.controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.wangsh.userscenter.common.controller.BaseController;
import com.wangsh.userscenter.common.util.EncryptUtil;
import com.wangsh.userscenter.service.users.api.IUsersService;
import com.wangsh.userscenter.service.users.pojo.AAdmins;
import com.wangsh.userscenter.service.users.pojo.AUsers;

/**
 * 未登陆页面
 * @author wangsh_sxt
 *
 */
@Controller
public class NoLoginController extends BaseController
{
	@Autowired
	private IUsersService usersService;
	
	/**
	 * 管理员登陆的页面
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/login.html")
	public String login(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		/* 接收页面参数 */
		String returnUrl = request.getParameter("returnUrl");
		if(returnUrl == null)
		{
			returnUrl = "" ;
		}
		AAdmins admins = (AAdmins) this.findObjfromSession(request, "1");
		if(admins != null)
		{
			/* 登陆成功处理页面跳转 */
			if(logSuccedReturnUrl(response, returnUrl, admins))
			{
				return null ; 
			}
			/* 用户已经登陆 */
			return "redirect:/head/users/main.html" ; 
		}
		returnUrl = URLEncoder.encode(returnUrl, "UTF-8");
		request.setAttribute("returnUrl", returnUrl);
		return "login";
	}
	
	/**
	 * 管理员登陆的提交页面
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/loginSubmit.html")
	public String loginSubmit(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		HttpSession session = request.getSession();
		/* 接收参数 */
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String code = request.getParameter("code");
		/* 登陆成功跳转的URL */
		String returnUrl = request.getParameter("returnUrl");
		
		/*图片验证码验证*/
		String randSess = session.getAttribute("randSess") + "";
		
		/* 移除验证码,防止重复使用 */
		session.removeAttribute("randSess");
		
		/* 验证码相同 */
		if(randSess.equalsIgnoreCase(code))
		{
			/* 查询数据库,处理业务逻辑 */
			Map<String, Object> condMap = new HashMap<String, Object>();
			condMap.put("email", email);
			AAdmins admins = this.usersService.findOneAdminsService(condMap);
			/* 检验邮箱 */
			if(admins != null)
			{
				/* 检验密码 */
				if(EncryptUtil.checkPassword(password, admins.getPassword()))
				{
					/* 校验状态 */
					if(admins.getStatus() == 1)
					{
						/* 登陆成功 */
						session.setAttribute("admins", admins);
						session.setAttribute("lastLoginTime", admins.getLastLoginTime());
						
						/* 修改管理员操作 */
						admins.setLoginCount(admins.getLoginCount() + 1);
						admins.setLastLoginTime(new Date());
						this.usersService.updateOneAdminsService(admins);
						
						/* 登陆成功处理页面跳转 */
						if(logSuccedReturnUrl(response, returnUrl, admins))
						{
							return null ; 
						}
						
						return "redirect:/back/admins/main.html" ; 
					}else
					{
						this.info = "账户状态为:" + admins.getStatusStr();
					}
				}else
				{
					this.info = "密码不正确" ; 
				}
				request.setAttribute("admins", admins);
			}else
			{
				this.info = "邮箱不存在" ; 
			}
		}else
		{
			this.info = "验证码不正确" ; 
		}
		request.setAttribute("returnUrl", returnUrl);
		request.setAttribute("info", info);
		return "login";
	}
	
	/**
	 * 单点登陆,returnUrl处理
	 * @param response
	 * @param returnUrl
	 * @param admins
	 * @return
	 * @throws IOException
	 */
	private boolean logSuccedReturnUrl(HttpServletResponse response, String returnUrl, AAdmins admins) throws IOException
	{
		if(returnUrl == null)
		{
			returnUrl = ""; 
		}
		returnUrl = URLDecoder.decode(returnUrl, "UTF-8");
		String ticket = UUID.randomUUID().toString() ; 
		admins.setTicketStr(ticket);
		this.usersService.addAdminsTicketService(admins);
		String ticketCond = "ticket=" + ticket ;
		String ticketIndex = "ticket=" ; 
		if(!"".equalsIgnoreCase(returnUrl))
		{
			/* 拼装处理returnUrl */
			if(returnUrl.indexOf(ticketIndex) != -1 )
			{
				String returnUrlStart = returnUrl.substring(0, returnUrl.indexOf(ticketIndex));
				String returnUrlEnd = returnUrl.substring(returnUrl.indexOf(ticketIndex) + ticketIndex.length(), returnUrl.length());
				if(returnUrlEnd.indexOf("&") != -1)
				{
					returnUrlEnd = returnUrlEnd.substring(returnUrlEnd.indexOf("&") + 1 , returnUrlEnd.length());
				}else
				{
					returnUrlEnd = "" ;
				}
				returnUrl = returnUrlStart + ticketCond + returnUrlEnd ; 
			}else if(returnUrl.indexOf("?") != -1)
			{
				/* 找到?,并且找到ticket */
				returnUrl += "&" + ticketCond ;
			}else
			{
				returnUrl += "?" + ticketCond ;
			}
		}
		
		/* 如果带了returnUrl,直接跳转returnUrl */
		if(!"".equalsIgnoreCase(returnUrl))
		{
			response.sendRedirect(returnUrl);
			return true ; 
		}
		return false ; 
	}
}
